<?php

//ini_set("error_reporting", E_ALL);
//ini_set("display_errors", TRUE);
//echo  "<br>user_id_txqq1:".$_SESSION['user_id_aa'];
//session_id("demo");
//请将下面信息更改成自己申请的信息
//echo "<br>user_id_aa3:".$_SESSION['user_id_aa'];

$_SESSION["appid"] = a_fanweC('TXQQ_KEY'); //opensns.qq.com 申请到的appid
$_SESSION["appkey"] = a_fanweC('TXQQ_SECRET'); //opensns.qq.com 申请到的appkey

if ($_REQUEST['oauth_txqq'] == '1') {
    include_once (VENDOR_PATH . 'user_login/txqq/get_request_token.php');
    //授权登录页
    $appid = a_fanweC('TXQQ_KEY');
    $redirect = "http://openapi.qzone.qq.com/oauth/qzoneoauth_authorize?oauth_consumer_key=$appid&";

    $result = array();
    $request_token = get_request_token(a_fanweC('TXQQ_KEY'), a_fanweC('TXQQ_SECRET'));
    parse_str($request_token, $result);

    //request token, request token secret 需要保存起来
    //在demo演示中，直接保存在全局变量中.真实情况需要网站自己处理
    $_SESSION["token"] = $result["oauth_token"];
    $_SESSION["secret"] = $result["oauth_token_secret"];

    $_SESSION["callback"] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . "/index.php?m=user&a=login_txqq&oauth_txqq=0&secret=" . $_SESSION['secret']; //QQ登录成功后跳转的地址	
    //获取request token


    if ($result["oauth_token"] == "") {
        //demo中不对错误情况做处理
        //网站需要自己处理错误情况
        exit;
    }

    //302跳转到授权页面
    $redirect .= "oauth_token=" . $result["oauth_token"] . "&oauth_callback=" . rawurlencode($_SESSION["callback"]);
    header("Location:$redirect");
} else {

    //exit;
    include_once (VENDOR_PATH . 'user_login/txqq/get_access_token.php');

    //echo "<br>user_id_aa4:" . $_SESSION['user_id_aa'];
    //tips//
    /**
     * QQ互联登录，授权成功后会回调此地址
     * 必须要用授权的request token换取access token
     * 访问QQ互联的任何资源都需要access token
     * 目前access token是长期有效的，除非用户解除与第三方绑定
     * 如果第三方发现access token失效，请引导用户重新登录QQ互联，授权，获取access token
     */
    //授权成功后，会返回用户的openid
    //检查返回的openid是否是合法id
    if (!is_valid_openid($_REQUEST["openid"], $_REQUEST["timestamp"], $_REQUEST["oauth_signature"])) {
        //demo对错误简单处理
        echo "###invalid openid\n";
        echo "sig:" . $_REQUEST["oauth_signature"] . "\n";
        exit;
    }

    //tips
    //这里已经获取到了openid，可以处理第三方账户与openid的绑定逻辑
    //但是我们建议第三方等到获取accesstoken之后在做绑定逻辑
    //用授权的request token换取access token
    $access_str = get_access_token($_SESSION["appid"], $_SESSION["appkey"], $_REQUEST['oauth_token'], $_REQUEST['secret'], $_REQUEST["oauth_vericode"]);
    //echo "access_str:$access_str\n";
    $result = array();
    parse_str($access_str, $result);

    //print_r($result);
    //error

    if (isset($result["error_code"])) {
        echo "error_code = " . $result["error_code"];
        print_r($result);
        exit;
    }

    //获取access token成功后也会返回用户的openid
    //我们强烈建议第三方使用此openid
    //检查返回的openid是否是合法id
    if (!is_valid_openid($result["openid"], $result["timestamp"], $result["oauth_signature"])) {
        //demo对错误简单处理
        echo "@@@invalid openid";
        echo "sig:" . $result["oauth_signature"] . "\n";
        exit;
    }

    //将access token，openid保存!!
    //XXX 作为demo,临时存放在session中，网站应该用自己安全的存储系统来存储这些信息
    $_SESSION["token"] = $result["oauth_token"];
    $_SESSION["secret"] = $result["oauth_token_secret"];
    $_SESSION["openid"] = $result["openid"];

    //第三方处理用户绑定逻辑
    //将openid与第三方的帐号做关联
    //bind_to_openid();
    $url_qq = "http://openapi.qzone.qq.com/user/get_user_info";
    $qqwb = array();
    $qqwb = json_decode(do_get($url_qq, a_fanweC('TXQQ_KEY'), a_fanweC('TXQQ_SECRET'), $_SESSION["token"], $_SESSION["secret"], $_SESSION["openid"]), true);
    $qqwb['openid'] = $_SESSION["openid"];
    $_SESSION['api_user_info'] = $qqwb;
    $user_data = $GLOBALS['db']->getRow("select * from " . DB_PREFIX . "user where txqq_id = '" . $qqwb['openid'] . "' and txqq_id <> ''");

    $names = $GLOBALS['db']->getRow("select * from " . DB_PREFIX . "user where user_name = '" . trim($qqwb ['nickname']) . "' ");
    $has_name = empty($names) ? 0 : 1;
    if (!$user_data && !$has_name) {
        $data ['user_name'] = trim($qqwb ['nickname']);
        $data ['user_pwd'] = md5(trim($qqwb ['nickname']));
        $data ['email'] = trim($qqwb ['nickname'] . '@qq.com');
        $data ['txqq_id'] = trim($qqwb ['openid']);
        $data ['status'] = 1;

        $data ['last_ip'] = $_SESSION['CLIENT_IP'];
        $data ['score'] = intval(a_fanweC("DEFAULT_SCORE"));
        $data ['status'] = a_fanweC('USER_AUTO_REG');
        $data ['create_time'] = a_gmtTime();
        $data ['update_time'] = a_gmtTime();
        $data ['group_id'] = a_fanweC("DEFAULT_USER_GROUP");

        $code = a_fanweC('INTEGRATE_CODE');
        if (empty($code))
            $code = 'fanwe';
        if ($code == 'ucenter') {
            $users = & init_users3_1();
            $users->need_sync = false;
            $is_add = $users->add_user(trim($data['user_name']), trim($data['user_pwd']), trim($data ['email']));
            if ($is_add) {
                $user_id_arr = $users->get_profile_by_name($_REQUEST ['user_name']);
                $data ['ucenter_id'] = $user_id_arr ['id'];
            }
        }
        $GLOBALS ['db']->autoExecute(DB_PREFIX . "user", addslashes_deep($data), 'INSERT');
        $rs = intval($GLOBALS ['db']->insert_id());
        if($rs)
        {
        	$score = intval ( $data ['score'] );
			$money = floatval ( $data ['money'] );
			if(!function_exists("s_user_money_log"))
			{
				require_once ROOT_PATH.'app/source/func/com_order_pay_func.php';
			}
			if ($money > 0)
				s_user_money_log ( $rs, $rs, 'User', $money, a_L ( "USER_ADD_USER" ), true );
	
			if ($score > 0)
				s_user_score_log ( $rs, $rs, 'User', $score, a_L ( "USER_ADD_USER" ), true );
        }
        
        $user_data = $GLOBALS['db']->getRow("select * from " . DB_PREFIX . "user where txqq_id = '" . $data['txqq_id'] . "' and txqq_id <> 0");
    }
    if ($user_data) {
        include_once(ROOT_PATH . 'app/source/func/com_user_func.php');
        user_do_login($user_data);
        exit;
    } else {

        $extend_fields = $GLOBALS ['db']->getAllCached("SELECT * FROM " . DB_PREFIX . "user_field where is_show = 1 order by sort desc");
        foreach ($extend_fields as $k => $v) {
            $extend_fields [$k] ['val_scope'] = explode(",", $v ['val_scope']);
        }
        $GLOBALS ['tpl']->assign("extend_fields", $extend_fields);

        $sql = "select id from " . DB_PREFIX . "article where type=1 and status=1";
        $id = $GLOBALS ['db']->getOneCached($sql);
        $agreement_url = a_u("Article/show", 'id-' . $id);

        $city_list = getGroupCityList();
        $GLOBALS ['tpl']->assign("city_list", $city_list);


        $GLOBALS ['tpl']->assign("agreement_url", $agreement_url);
        $GLOBALS ['tpl']->assign('redirect', $_REQUEST ['redirect']);
        $GLOBALS ['tpl']->assign('goods_id', $_REQUEST ['id']);

        $GLOBALS ['tpl']->assign('user_api_field_name', 'txqq_id');
        $GLOBALS ['tpl']->assign('user_api_field_value', $qqwb['openid']);

        //输出主菜单
        $GLOBALS ['tpl']->assign("main_navs", assignNav(2));
        //输出城市
        $GLOBALS ['tpl']->assign("city_list", getGroupCityList());
        //输出帮助
        $GLOBALS ['tpl']->assign("help_center", assignHelp());

        $data = array('navs' => array(array('name' => a_L("HC_PLEASE_REG_OR_REGISTER"), 'url' => '')), 'keyword' => '', 'content' => '');

        $code = a_fanweC('INTEGRATE_CODE');
        if (empty($code))
            $code = 'fanwe';
        if ($code == 'ucenter') {
            $users = & init_users3_1();
            $users->need_sync = false;
            $is_add = $users->add_user(trim($data['user_name']), trim($data['user_pwd']), trim($data ['email']));
            if ($is_add) {
                $user_id_arr = $users->get_profile_by_name($_REQUEST ['user_name']);
                $data ['ucenter_id'] = $user_id_arr ['id'];
            }
        }


        assignSeo($data);
        $GLOBALS['tpl']->display('Inc/user/login_sync.moban');
    }
}

function &init_users3_1() {
    $set_modules = false;
    static $cls = null;
    if ($cls != null) {
        return $cls;
    }
    $code = a_fanweC('INTEGRATE_CODE');
    if (empty($code))
        $code = 'fanwe';
    $code = $code . '3';
    include_once (VENDOR_PATH . 'integrates3/' . $code . '.php');
    $cfg = unserialize(a_fanweC('INTEGRATE_CONFIG'));
    $cls = new $code($cfg);

    return $cls;
}

?>